<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="机台类型" v-if="permissionStore.hasPermisson('ppzl.cx')">
                            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                                v-model="pageData.dropDownData" @press-enter="huiche" />
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar class="gesture" :items="pageData.btnList" @add="addHandler" @del="deleteHandler"
                        @select="selectHandler">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                    @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef" class="ag-theme-alpine"
                    :rowData="table.dataList" :localeText="localeText1" :columnDefs="tc" @columnResized="onColumnResized"
                    @columnMoved="onColumnMoved"></AgGridVuesCopys>
                    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="size"
            :current="page" />
            </a-spin>
        </template>
        <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
            :width="400" :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="80px" label="机台类型" field="machineType"
                        :rules="[{ required: true, message: '机台类型必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" v-model="dataForm.machineType" :loading="loading1" :allowClear="true"
                            @search="handleSearch1" :filter-option="false" allow-search @focus="focusSel1">
                            <a-option v-for="item in pageData.typeList">{{ item.typeName }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="维修原因" field="repairCause"
                        :rules="[{ required: true, message: '维修原因必填' }]" :validate-trigger="['change', 'blur']">
                        <a-textarea class="bacClass" placeholder="" v-model="dataForm.repairCause" :max-length="400"
                            allow-clear show-word-limit />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="是否开启" field="ifOpen">
                        <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9" v-model="dataForm.ifOpen"
                            checked-value="1" unchecked-value="0" style="width: 65px">
                            <template #checked> 停用 </template>
                            <template #unchecked> 开启 </template>
                        </a-switch>
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>
  
<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { pagingList } from '@/api/paging'
// 引入

import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

interface BrandInfo {
    "id": any
    "num": any
    "machineType": any
    "ifOpen": any
    "repairCause": any
}

export default {
    name: 'RepairReasonMaintenance',

    setup() {
        const total = ref(0)
        const page = ref(1)
        const size = ref(10)
        function PageSize(val: any) {
            page.value = val
            doRefresh()
        }
        function change1(val: any) {
            size.value = val
            doRefresh()
        }
        const headerShow = ref<boolean>(true)

        function doRefresh() {
            pageData.pageLoading = true
            updateGridState01()
            post({
                url: 'temRepair/repair/findRepairPage',
                data: {
                    page: page.value,
                    limit: size.value,
                    machineType: pageData.dropDownData
                },
            })
                .then(({ data, code,message }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list)

                        // 查询方法改

                        gridOption.value.setRowData(data.list)

                        total.value = data.total
                    }else{
                        Message.error(message)
                    }
                })
                .catch(console.log)
                .finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection()
        const pagination = usePagination(doRefresh)
        const table = useTable()
        const rowKey = useRowKey('id')
        const tableColumns = useTableColumn([
            {
                title: '序号',
                key: 'num',
                dataIndex: 'num',
                width: 150,
            },

            {
                title: '机台类型',
                key: 'machineType',
                dataIndex: 'machineType',
                width: 150,
            },
            {
                title: "维修原因",
                key: "repairCause",
                dataIndex: "repairCause",
                width: 150
            },
            {
                title: '创建人',
                key: 'createName',
                dataIndex: 'createName',
                width: 150,
            },
            {
                title: '创建时间',
                key: 'createTime',
                dataIndex: 'createTime',
                width: 200,
            },
            {
                title: '最后修改人',
                key: 'updateName',
                dataIndex: 'updateName',
                width: 150,
            },
            {
                title: '最后修改时间',
                key: 'updateTime',
                dataIndex: 'updateTime',
                width: 200,
            },
            {
                title: "是否开启",
                key: "ifOpen",
                dataIndex: "ifOpen",
                width: 100,
                slotName: "ifOpen",
                fixed: 'right'
            },
            {
                title: '操作',
                key: 'id',
                slotName: 'act',
                width: 150,
                fixed: 'right',
            },
        ])

        let tc: any[] = tableColumns.map((o) => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed'],
                tooltipField: o.key,
            }

            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj['lockPosition'] = 'right'
                obj['width'] = 90
                obj['cellRenderer'] = {
                    template: `<a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            e: permissionStore.hasPermisson('wxyy.xg'),
                            a,
                        }
                    },
                }
            }
            if (o.slotName === 'ifOpen') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj['lockPosition'] = 'right'
                obj['width'] = 90
                obj['cellRenderer'] = {
                    template: `
                        <a-space>
                        <el-tag type="success" @click="a" v-if="a==0">
                            {{val}}
                        </el-tag>
                        <el-tag type="info" @click="b" v-if="a==1">
                            {{val}}
                        </el-tag></a-space>`,
                    setup(props: any) {
                        let val = ref()
                        if (props.params.data.ifOpen == 0) {
                            val.value = '开启'
                        } else {
                            val.value = '停用'
                        }

                        return {
                            val,
                            a: props.params.data.ifOpen,
                        }
                    },
                }
            }

            return obj
        })

        let a = [
            {
                showRowGroup: 'hide_def',
                headerName: '',
                checkboxSelection: true,
                headerCheckboxSelection: true,
                pinned: 'left',
                width: 50,
                resizable: false,
                filter: false,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: 'left',
            },
        ]
        tc = a.concat(tc)
        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            nameList: []
            pageLoading: boolean
            typeList: any[]
            dropDownData1: any
            rHeight: any
            btnList: any[]
            isEdit: boolean
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增维修原因码',
            dropDownData: '',
            pageLoading: false,
            typeList: [],
            dropDownData1: '',
            rHeight: 0,
            btnList: [],
            isEdit: false,
        })

        interface gcType {
            id: any
            company: any
        }

        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ brandName: '', deleteState: 0 })
        }
        //下拉数据
        const options = ref<any>(pageData.nameList)
        const loading = ref(false)
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { brandName: value, deleteState: 0 }
                loading.value = true
                selCxAll(ob)
                options.value = pageData.nameList
                loading.value = false
            } else {
                options.value = []
            }
        }

        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: 'product/Brand/getFieldValue',
                data: val,
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    let dataList: any = []
                    data.forEach(function (o: any) {
                        dataList.push(o['brandName'])
                    })
                    pageData.nameList = dataList
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
        }

        onMounted(() => {
            selectHandler()
        })
        let cxbl = ''
        //查询
        const selectHandler = () => {
            page.value = 1
            cxbl = pageData.dropDownData
            doRefresh()
        }
        const queryData = reactive({
            clothType: '',
        })
        const addHandler = () => {
            selCxAll1({ typeName: "" })
            for (var key in dataForm) {
                dataForm[key] = null
            }

            pageData.showAdd = true
            pageData.sideTitle = '新增维修原因码'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "num": null,
            "machineType": null,
            "ifOpen": 1,
            repairCause: null
        })

        // 表格准备事件
        const gridOption = ref()
        const colState = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState.value = params.columnApi
        }

        let formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    pageData.pageLoading = true
                    if (pageData.sideTitle === '新增维修原因码') {
                        post({
                            url: 'temRepair/repair/saveRepair',
                            data: [dataForm],
                        })
                            .then((res: any) => {
                                if (res.code === 200) {
                                    formRef.value?.resetFields()
                                    pageData.showAdd = false

                                    Message.success({
                                        content: '新增成功',
                                        duration: 5000,
                                    })
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000,
                                    })
                                }
                                doRefresh()
                            })
                            .finally(() => {
                                doRefresh()
                                pageData.pageLoading = false
                            })
                    } else {
                        post({
                            url: 'temRepair/repair/updateRepair',
                            data: [dataForm],
                        })
                            .then((res: any) => {
                                if (res.code === 200) {
                                    formRef.value?.resetFields()
                                    pageData.showAdd = false
                                    Message.success({
                                        content: '修改成功',
                                        duration: 5000,
                                    })
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000,
                                    })
                                }
                            })
                            .finally(() => {
                                doRefresh()
                                pageData.pageLoading = false
                            })
                    }
                }

            })
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }

            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true
                    post({
                        url: 'temRepair/repair/deleteRepair',
                        data: gridOption.value.getSelectedRows().map((o: any) => {
                            return o.id
                        }),
                    })
                        .then(({ code, data }: any) => {
                            if (code === 200) {
                                Message.success({
                                    content: '删除成功',
                                    duration: 5000,
                                })
                                pagination.page = 1
                                doRefresh()
                            } else {
                                Message.error({
                                    content: '删除失败',
                                    duration: 5000,
                                })
                            }
                        })
                        .finally(() => {
                            pageData.pageLoading = false
                        })
                },
            })
        }

        let curobj = null
        const editHandler = (record: BrandInfo) => {
            curobj = record
            selCxAll1({ typeName: "" })
            for (let key in record) {
                dataForm[key] = record[key]
            }
            pageData.sideTitle = '修改维修原因码'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>((resolve) => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值不能包含中文！')
                }
                resolve()
            })
        }


        //下拉数据
        const options1 = ref<any>(pageData.typeList)
        const loading1 = ref(false)
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = { typeName: value }
                loading.value = true
                selCxAll1(ob)
                options.value = pageData.typeList
                loading.value = false
            } else {
                options.value = []
            }
        }

        //下拉框查询 机器类型
        function selCxAll1(val: any) {
            post({
                url: 'aps/dwMachineType/getFieldValue',
                data: val,
            }).then((res: any) => {
                if (res.code === 200) {
                    pageData.typeList = res.data
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ typeName: "" })
        }
        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('wxyy.cx')) {
            pageData.btnList.push('查询')
        }
        if (permissionStore.hasPermisson('wxyy.xz')) {
            pageData.btnList.push('新增')
        }
        if (permissionStore.hasPermisson('wxyy.sc')) {
            pageData.btnList.push('删除')
        }

        const handleChange = (_data: any) => {
            table.handleSuccess(_data)
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        const huiche = () => {
            page.value = 1
            cxbl = pageData.dropDownData
            doRefresh()
        }
        const pagingList1: any = ref(pagingList)
        const localeText1: any = ref(localeText)
        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('RepairReasonMaintenance002', gridOption, colState, tc)
        const onColumnMoved = () => {
            saveGridState01()
        }
        const onColumnResized = () => {
            saveGridState01()
        }
        return {
            saveOrUpdateGridState01,
            saveGridState01,
            updateGridState01,
            onColumnMoved,
            onColumnResized,
            colState,
            pagingList1,
            huiche,
            localeText1,
            defaultColDef,
            tc,
            total,
            PageSize,
            change1,
            page,
            size,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            options,
            loading,
            handleSearch,
            focusSel,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            headerShow,
            handleChange,
            gridReady,
            permissionStore,
        }
    },
    components: { Toolbar, PageTabelLayout,  },
}
</script>
  